<template>
  <el-card style="width:100%;height: 100%;">

    <el-row>
        <el-col :span="12">
            <div style="text-align: left;">
                <el-button plain type="primary" size="mini" @click="dialogFormVisible = true" style="height: 40px"><i class="
el-icon-circle-plus"> </i> 新增</el-button>
            </div>
            
        </el-col>
        <el-col :span="12">
            <el-col :span="14" :offset="4">
                <div style="text-align: left;">
                    <el-input v-model="input" placeholder="请输入内容"  style="height: 100%;"></el-input>
                </div></el-col>
            <el-col :span="6"><div style="text-align: left;">
                <el-button size="mini" type="primary" style="height: 40px" @click="searchitem">搜索</el-button>
            </div></el-col>
            
            
        </el-col>
    </el-row>


    <el-row>
        <el-table
          :data="filterData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="date"
            label="日期"
            width="140">
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="80">
          </el-table-column>
          <el-table-column
            prop="province"
            label="省份"
            width="80">
          </el-table-column>
          <el-table-column
            prop="city"
            label="市区"
            width="80">
          </el-table-column>
          <el-table-column
            prop="address"
            label="地址"
            width="160">
          </el-table-column>
          <el-table-column
            prop="zip"
            label="邮编"
            width="80">
          </el-table-column>
          <el-table-column
            label="操作"
            width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>

           
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
           
          </el-table-column>
        </el-table>
    </el-row>
    <p style="height:100px"></p>

    <el-row>
      <el-pagination 
     @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
     :current-page="currentPage"
     :page-sizes="[5,3,2]" 
     :page-size="pagesize"
     layout="total, sizes, prev, pager, next, jumper"
     :total="filterData.length">
   </el-pagination>
    </el-row>

    <!-- 新增模态框 -->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible" center>
      <el-form :model="form">
        <el-form-item label="日期" label-width="80px">
          <el-col :span="15">
            <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="年/月/日"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;">
            </el-date-picker>
            
          </el-col>
          
        </el-form-item>
         <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-col :span="15">
             <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-col>
         
        </el-form-item>
        <el-form-item label="省市" :label-width="formLabelWidth">
          <el-col :span="15">
           <el-cascader
            size="large"
            :options="pcTextArr"
            v-model="selectedOptions"
            style="width: 100%;"
            >
          </el-cascader>
          </el-col>
         
        </el-form-item>
         <el-form-item label="地址" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-col>
          
        </el-form-item>
         <el-form-item label="邮编" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="form.zip" autocomplete="off"></el-input>
          </el-col>
          
        </el-form-item>
        
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addinfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改模态框 -->
    <el-dialog title="修改用户" :visible.sync="dialogEditVisible" center>
      <el-form :model="form">
        <el-form-item label="日期" label-width="80px">
          <el-col :span="15">
            <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="年/月/日"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;">
            </el-date-picker>
            
          </el-col>
          
        </el-form-item>
         <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-col :span="15">
             <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-col>
         
        </el-form-item>
        <el-form-item label="省市" :label-width="formLabelWidth">
          <el-col :span="15">
           <el-cascader
            size="large"
            :options="pcTextArr"
            v-model="selectedOptions"
            style="width: 100%;"
            >
          </el-cascader>
          </el-col>
         
        </el-form-item>
         <el-form-item label="地址" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-col>
          
        </el-form-item>
         <el-form-item label="邮编" :label-width="formLabelWidth">
          <el-col :span="15">
            <el-input v-model="form.zip" autocomplete="off"></el-input>
          </el-col>
          
        </el-form-item>
        
      </el-form>
      <div slot="footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateinfo">确 定</el-button>
      </div>
    </el-dialog>

  </el-card>
   
  


  </template>
  
  <script>
  import {
  provinceAndCityData,
  pcTextArr
} from "element-china-area-data";
import user from '@/api/user' 

  export default {
      name:'UserView',
      data(){
          return{
            provinceAndCityData,
            pcTextArr,
            selectedOptions: [], //["湖北省","武汉市"]
            dialogFormVisible:false, //新增用户模态框的可见性
            dialogEditVisible:false, //修改用户模态框的可见性
            formLabelWidth:'80px', //表单标签的宽度
            current_id: '', //正在修改的用户id
            form:{
              date:'',
              name:'',
              province:'',
              city:'',
              address:'',
              zip:''
            },
            currentPage: 1, //当前显示第几页
            currentIndex: '',
            pagesize: 5, //每页显示多少条 pagesizes数组是可以动态改变每页显示多少条
            visible:false,
            input:'', //搜索关键词
            tableData: [{
              id:'001',
              date: '2016-05-02',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1518 弄'
            }, {
              id:'002',
              date: '2016-05-04',
              name: '王小虎',
              address: '上海市普陀区金沙江路 1517 弄'
            }],
            //filterData:[]
          }
      },
      computed:{
        //搜索功能
        filterData:{
          get(){
            if(this.input == ''){
              return this.tableData
            }
            else{
              return this.tableData.filter(item=>{
                return item.name.indexOf(this.input) != -1
              })
            }
          },
          set(newValue){
            //print('set',newValue)
            this.$set(this.tableData, newValue);
          }
         
        },
      },
      methods:{
        searchitem(){
          if(this.input == ''){
            this.filterData =  this.tableData
          }
          else{
            this.filterData = this.tableData.filter(item=>{
              return item.name.indexOf(this.input) != -1
            })
          }
        },
        updateinfo(){//修改用户
          this.dialogEditVisible = false
          //构建表单
          let info = {
            id: this.form.id,
            date: this.form.date,
            name: this.form.name,
            province: this.selectedOptions[0],
            city: this.selectedOptions[1],
            address: this.form.address,
            zip: this.form.zip
          }

          const formData = new FormData();
          for (var key in info) {
            formData.append(key, info[key]);
          }

          user.update_user(formData).then(res=>{
            if(res.data.code == 200){
              this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.getinfo()
            }
            else{
              this.$message.error('修改失败')
            }
           
          })
        },

        addinfo(){
          this.dialogFormVisible = false
          //构建表单
          let info = {
            date: this.form.date,
            name: this.form.name,
            province: this.selectedOptions[0],
            city: this.selectedOptions[1],
            address: this.form.address,
            zip: this.form.zip
          }

          const formData = new FormData();
          for (var key in info) {
            formData.append(key, info[key]);
          }

          user.add_user(formData).then(res=>{
            console.log(res)
            this.$message({
              message: '添加成功',
              type: 'success'
            });
            this.getinfo()
          })
        
        },
        getinfo(){//获取数据
          user.get_user().then(res=>{
            if (res.data.code == 200) {
              console.log(res.data.data)
              this.tableData = res.data.data
              this.filterData = this.tableData
            }
            else{
              this.$message.error('获取数据失败')
            }
          })
        },
        
        handleSizeChange(val) {
          this.pagesize = val;
          console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
          this.currentPage= val
          console.log(`当前 ${val} 页`);
        },
        handleEdit(index, row) {//点击修改按钮

          console.log(index, row);//row是当前行的数据，包括没有显示的数据（如id）
          this.dialogEditVisible = true
          this.form = row//将当前行的数据赋值给form，令修改模态框中的表单显示当前行的数据
          console.log('form',this.form)
          this.selectedOptions = [row.province,row.city] //省市级联选择器需要单独处理
        },
        handleDelete(index, row) {//点击删除按钮
          console.log(index, row);
          this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            user.delete_user(row.id).then(res=>{
              console.log(res.data.msg)
              if(res.data.code == 200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.tableData.splice(index,1)
                this.getinfo()
                console.log('个数',this.tableData.length)
                console.log('页大小',this.pagesize)
                console.log('当前',this.currentPage)
                let totalPage = Math.ceil((this.tableData.length)/this.pagesize)
                console.log('页个数',totalPage)
                let currentPage = this.currentPage > totalPage ? totalPage : this.currentPage
                this.currentPage = currentPage<1 ? 1 : currentPage
                
                console.log(this.currentPage)
              }
              else{
                this.$message({
                  type: 'error',
                  message: '删除失败!'
                });
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
        }
      },
      mounted(){
        this.getinfo()
      }
  }
  </script>
  
  <style>
  
  </style>